package com.phuonghoang.vnexpress;

import java.util.List;

import com.phuonghoang.adapter.CatergoryVnexpressAdapter;
import com.phuonghoang.model.RssItem;
import com.phuonhoang.utils.RssParser;
import com.phuonhoang.utils.Variables;

import android.R.integer;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;

@SuppressWarnings("unused")
public class VnexpressActivity extends ListActivity {
	private int paper;
	private ProgressDialog dialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		Bundle bundle = getIntent().getExtras();
		paper = bundle.getInt(Variables.PAPER);
		setTitle(Variables.PAPERS[paper]);
		CatergoryVnexpressAdapter adapter = new CatergoryVnexpressAdapter(this,
				Variables.ICONS[paper], Variables.CATEGORIES[paper]);
		setListAdapter(adapter);
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		// TODO Auto-generated method stub
		super.onListItemClick(l, v, position, id);
		int key = paper * 1000 + position;
		if (Variables.newMap.get(key) == null) {
			dialog = ProgressDialog.show(VnexpressActivity.this, "", "Loading.."
					+ Variables.CATEGORIES[paper][position]);
			
			new VnexpressTask().execute(position);
		}
		else{
			Intent intent = new Intent(VnexpressActivity.this, NewListVnexpressActivity.class);
			intent.putExtra(Variables.PAPER, paper);
			intent.putExtra(Variables.CATEGORIE, position);
			startActivity(intent);
		}
		
		
		//Toast.makeText(getBaseContext(), ""+items.size(), Toast.LENGTH_SHORT).show();
		

	}
	class VnexpressTask extends AsyncTask<Integer, Void, Void>{
		private int position;
		@Override
		protected Void doInBackground(Integer... params) {
			position= params[0];
			int key = paper * 1000 + position;
			RssParser parser = new RssParser();
			List<RssItem> items = parser
					.getNewList(Variables.LINKs[paper][position]);
			//System.out.println("Rss size" + items.size());
			Variables.newMap.put(key, items);
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			if (dialog != null) {
				dialog.dismiss();
			}
			Intent intent = new Intent(VnexpressActivity.this, NewListVnexpressActivity.class);
			intent.putExtra(Variables.PAPER, paper);
			intent.putExtra(Variables.CATEGORIE, position);

			startActivity(intent);
			super.onPostExecute(result);
		}
		
	}

}
